var uls = document.querySelector('.nav_right');
var id = localStorage.getItem('id')
var token = localStorage.getItem('token')

if (id && token) {


    // 修改list的连接
    // document.querySelector('.list').setAttribute('href', "list.html?token=" + token + '&id=' + id)
    // 发送ajax获取用户信息
    var xhr = new XMLHttpRequest;
    xhr.open('get', `http://localhost:8888/users/info/${id}`)
    xhr.setRequestHeader('authorization', token)
    xhr.send()
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
                var res = xhr.responseText;
                res = JSON.parse(res)
                var { code, info: { username } } = res;
                // console.log(res);
                uls.innerHTML = `
                    <li>
                        <a class="brli1" style="color:red">${username}</a>
                    </li>
                    </li>
                    <li>
                        <a>我的订单</a>
                    </li>
                    <li>
                        <a>我的京东</a>
                    </li>
                    <li>
                        <a>京东会员</a>
                    </li>
                    <li>
                        <a>企业采购</a>
                    </li>
                    <li>
                        <a>客户服务</a>
                    </li>
                    <li>
                        <a>网站导航</a>
                    </li>
                    <li>
                        <a>手机京东</a>
                    </li>
                  
                `
            }
        }
    }
}

uls.onclick = function () {
    var target = window.event.target || window.event.srcElement;
    if (target.className === 'logout') {
        var xhr = new XMLHttpRequest;
        xhr.open('get', 'http://localhost:8888/users/logout/' + target.getAttribute('data-id'))
        xhr.setRequestHeader('authorization', target.getAttribute('token'))
        xhr.send()
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    var res = xhr.responseText;
                    res = JSON.parse(res)
                    console.log(res);
                    var { code, message } = res;
                    if (code === 1) {
                        alert(message)
                        // 将内容换成登录注册
                        location.href = "home.html"
                    }
                }
            }
        }
    }
}


//获取本地存储
var data = localStorage.getItem('data')
// console.log(data);
var cen = document.querySelector('.box2 .cen1')

var data = JSON.parse(data)
// console.log(data);

var cen = document.querySelector('.box2 .cen1')

// console.log(bot);
promiseAjax({
    url: '/abcd',
}).then(res => {

    // console.log(res);
    var { list } = res
    // console.log(list);

    //------------------------------------------------------------------
    var str = ''
    for (var i = 0; i < data.length; i++) {
        console.log(data[i].shoppid);
        // console.log(data[i].num);
        list.forEach(item => {
            var zzhe = /^h/
            //通过正则判断id
            if (zzhe.test(data[i].shoppid) === true) {
                if (data[i].shoppid === item.deal_hid) {
                    // console.log(item);
                    var { deal_img, deal_global, deal_tit } = item
                    // console.log(deal_img, deal_global, deal_tit);
                    var { price_home } = deal_global
                    // console.log(price_home);

                    str += `
                    <div>
                        <ul>
                            <li><input type="checkbox" name="selectOne"></li>
                            <li>
                                <img src="${deal_img}">
                            </li>
                            <li>${deal_tit}</li>
                            <li style="color:red" >
                             ￥<span class="price">${price_home}</span>元
                            </li>
                            <li>
                                <button class="reduce">-</button>
                                <input type="number" value="${data[i].num}" name="number">
                                <button class="add">+</button>
                            </li>
                            <li style="color:red">
                            ￥<span class="subtotal" style="color:red">${price_home * data[i].num}</span>元
                            </li>
                            <li><button class="remove" id=${item.deal_hid}>删除购物车</button></li>
                        </ul>
                    </div>

                `
                    cen.innerHTML = str
                    //全选
                    select()
                    //加減
                    handlerNumber()
                    //小计，价格
                    count()
                    //删除
                    remove()

                }
            } else {
                if (data[i].shoppid === item.deal_hid) {
                    // console.log(item);
                    var { deal_img, deal_group, deal_tit } = item
                    // console.log(deal_img, deal_group, deal_tit);
                    var { price_dis } = deal_group
                    // console.log(price_dis);
                    // console.log(price_dis * data[i].num);

                    str += `
                        <div>
                            <ul>
                                <li><input type="checkbox" name="selectOne"></li>
                                <li>
                                    <img src="${deal_img}">
                                </li>
                                <li>${deal_tit}</li>
                                <li style="color:red" >
                                ￥<span class="price">${price_dis}</span>元
                                </li>
                                <li>
                                    <button class="reduce">-</button>
                                    <input type="number" value="${data[i].num}" name="number">
                                    <button class="add">+</button>
                                </li>
                                <li style="color:red">
                                ￥<span class="subtotal" style="color:red">${price_dis * data[i].num}</span>元
                                </li>
                                <li><button class="remove" id=${item.deal_hid}>删除购物车</button></li>
                            </ul>
                        </div>

                    `

                    cen.innerHTML = str
                    //全选
                    select()
                    //加減
                    handlerNumber()
                    //小计，价格
                    count()
                    //删除
                    remove()
                }

            }
        })
    }
})

//计算小计和总数量总价格的函数
function count() {
    var number = document.querySelectorAll('[name="number"]');
    var prices = document.querySelectorAll('.price');
    var subtotals = document.querySelectorAll('.subtotal');
    // console.log(number);
    // console.log(subtotals);
    // console.log(prices[0].innerText);
    for (var i = 0; i < number.length; i++) {
        subtotals[i].innerText = (prices[i].innerText - 0) * (number[i].value - 0)
    }
    //计算总数量
    var n = 0;
    var p = 0
    var selectOne = document.querySelectorAll('[name="selectOne"]');
    //转数组
    var arr = [].slice.call(selectOne)
    // console.log(arr);
    var brr = arr.filter(item => item.checked)
    // console.log(brr);
    brr.forEach((v, i) => {
        var num = v.parentElement.parentElement.querySelector('[name="number"]').value - 0;
        n += num

        var price = v.parentElement.parentElement.querySelector('.subtotal').innerText - 0;
        p += price
    })
    document.querySelector('.totalNum').innerText = n;
    document.querySelector('.totalPrice').innerText = p;
    // console.log(p);

}

// 数量加减的功能
function handlerNumber() {
    //给减绑定事件
    var reduces = document.querySelectorAll('.reduce');
    for (var i = 0; i < reduces.length; i++) {
        reduces[i].onclick = function () {


            //先获取当前减按钮的下一个兄弟标签 -放数量的那个input中的值
            var num = this.nextElementSibling.value - 0;
            //自减
            num--;
            //限定最小值
            if (num <= 1) {
                num = 1
            }
            //降自减以后的数字放回到input中
            this.nextElementSibling.value = num
            count()
        }
    }
    //给加绑定事件
    var adds = document.querySelectorAll('.add');
    for (var i = 0; i < adds.length; i++) {
        adds[i].onclick = function () {
            //先获取当前加按钮的上一个兄弟标签 -放数量的那个input中的值
            var num = this.previousElementSibling.value - 0;
            //自增
            num++;
            //限制最大值
            //获取库存
            //  var stock = this.parentElement.parentElement.lastElementChild.getAttribute('data-stock')
            //  if (num >= stock) {
            //      num = stock
            //  }
            //将自减以后的数字放回到input中
            this.previousElementSibling.value = num;
            //发送请求 -将数据库中的数量进行修改
            //获取当前商品的id
            //  var goodsid = this.parentElement.parentElement.lastElementChild.getAttribute('data-id')
            //  editNumber(userIdArr, goodsid, num, token)
            count()
        }
    }
}

function remove() {
    const removes = document.querySelectorAll('.remove')
    console.log(removes);
    for (var i = 0; i < removes.length; i++) {

        removes[i].onclick = function () {
            console.log(this);
            data.forEach((v, index) => {
                console.log(v.shoppid);
                console.log(this.getAttribute('id'));
                if (v.shoppid === this.getAttribute('id')) {
                    data.splice(index, 1)
                    localStorage.setItem('data', JSON.stringify(data))
                    this.parentElement.parentElement.parentElement.remove()
                }
            })
        }
    }
}

//单选全选功能
function select() {
    //全选功能
    var selectAll = document.querySelectorAll('[name="selectAll"]');
    var selectOne = document.querySelectorAll('[name="selectOne"]');
    //给所有全选按钮绑定单机事件
    for (var i = 0; i < selectAll.length; i++) {
        selectAll[i].onclick = function () {
            //设置所有的单选
            for (var j = 0; j < selectOne.length; j++) {
                selectOne[j].checked = this.checked
            }
            //设置所有的全选
            for (var j = 0; j < selectAll.length; j++) {
                selectAll[j].checked = this.checked
            }
            count()
        }

    }
    //给所有的单选绑定事件
    for (var i = 0; i < selectOne.length; i++) {
        selectOne[i].onclick = function () {
            //判断是否所有单选全部选中了
            //将所有的单选 - 集合-转成数组-调用every方法判断是否全部
            var arr = [].slice.call(selectOne)
            var bool = arr.every(item => item.checked)
            //设置所有的全选
            for (var j = 0; j < selectAll.length; j++) {
                selectAll[j].checked = bool
            }
            count()
        }
    }
}

